package com.mall.user.services;

import com.mall.commons.tool.exception.ValidateException;
import com.mall.user.ILoginService;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.converter.MemberConverter;
import com.mall.user.dal.entitys.Member;
import com.mall.user.dal.entitys.UserVerify;
import com.mall.user.dal.persistence.MemberMapper;
import com.mall.user.dal.persistence.UserVerifyMapper;
import com.mall.user.dto.*;
import com.mall.user.utils.JwtTokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
@Component
@Slf4j
public class LoginServiceImpl implements ILoginService {
    @Autowired
    MemberMapper memberMapper;

    @Autowired
    MemberConverter memberConverter;

    @Autowired
    UserVerifyMapper userVerifyMapper;


    @Override
    public UserLoginResponse Login(UserLoginRequest request) {
        UserLoginResponse response = new UserLoginResponse();
        try {
            request.requestCheck();
            String password = request.getPassword();
            String pwd = DigestUtils.md5DigestAsHex(password.getBytes());

            Example example = new Example(Member.class);
            example.createCriteria().andEqualTo("username" , request.getUserName()).andEqualTo("password" , pwd);
            List<Member> members = memberMapper.selectByExample(example);
            if (members.size() == 0){
                response.setCode(SysRetCodeConstants.USERORPASSWORD_ERRROR.getCode());
                response.setMsg(SysRetCodeConstants.USERORPASSWORD_ERRROR.getMessage());
                return response;
            }
            Member member = members.get(0);
            if (!member.getIsVerified().equals("Y")){
                response.setCode(SysRetCodeConstants.USER_ISVERFIED_ERROR.getCode());
                response.setMsg(SysRetCodeConstants.USER_ISVERFIED_ERROR.getMessage());
                return response;
            }

            response = memberConverter.member2LoginRes(member);
            response.setCode(SysRetCodeConstants.SUCCESS.getCode());
            response.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            Long id = response.getId();
            String username = response.getUsername();
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append(id);
            stringBuffer.append(",");
            stringBuffer.append(username);
            response.setToken(JwtTokenUtils.builder().msg(stringBuffer.toString()).build().creatJwtToken());
        } catch (Exception e) {
            e.printStackTrace();
            response.setCode(SysRetCodeConstants.SYSTEM_ERROR.getCode());
            response.setMsg(SysRetCodeConstants.SYSTEM_ERROR.getMessage());
        }

        return response;
    }

    @Override
    public UserVerifyResponse selectVerify(String uuid) {

        UserVerifyResponse userVerifyResponse = new UserVerifyResponse();
        try {
            Example example = new Example(UserVerify.class);
            example.createCriteria().andEqualTo("uuid" , uuid);

            List<UserVerify> userVerifies = userVerifyMapper.selectByExample(example);
            UserVerify userVerify = userVerifies.get(0);

            userVerifyResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            userVerifyResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            userVerifyResponse.setUid(userVerify.getId());
            userVerifyResponse.setUsername(userVerify.getUsername());
        } catch (Exception e) {
            userVerifyResponse.setCode(SysRetCodeConstants.DATA_NOT_EXIST.getCode());
            userVerifyResponse.setMsg(SysRetCodeConstants.DATA_NOT_EXIST.getMessage());
        }

        return userVerifyResponse;
    }

    @Override
    public CheckAuthResponse validToken(CheckAuthRequest checkAuthRequest) {
        CheckAuthResponse checkAuthResponse = new CheckAuthResponse();
        String token = checkAuthRequest.getToken();
        try {
            String result = JwtTokenUtils.builder().token(token).build().freeJwt();
            String[] split = result.split(",");
            Long uid = Long.valueOf(split[0]);
            String username = split[1];
            checkAuthResponse.setCode(SysRetCodeConstants.SUCCESS.getCode());
            checkAuthResponse.setMsg(SysRetCodeConstants.SUCCESS.getMessage());
            checkAuthResponse.setUserInfo(uid);
            checkAuthResponse.setUsername(username);

        } catch (ValidateException validateException) {
            checkAuthResponse.setCode(validateException.getErrorCode());
            checkAuthResponse.setMsg(validateException.getMessage());
        }

        return checkAuthResponse;
    }
}
